<template>
  <CustomScrollbar class="favorites-scroll">
    <div class="favorites">
    <div class="header">
      <div class="cover-gradient">
        <span class="icon">♥</span>
      </div>
      <div class="info">
        <p class="type">播放列表</p>
        <h1 class="title">我喜欢的音乐</h1>
        <p class="stats">{{ favorites.length }} 首歌曲</p>
      </div>
    </div>
    
    <div class="content">
      <div class="actions">
        <button class="play-all-btn" @click="playAllFavorites" :disabled="favorites.length === 0">
          <span>▶</span> 播放全部
        </button>
        <button class="refresh-btn" @click="loadFavorites" title="刷新收藏列表">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M8 3a5 5 0 1 0 4.546 2.914.5.5 0 0 1 .908-.417A6 6 0 1 1 8 2v1z"/>
            <path d="M8 4.466V.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L8.41 4.658A.25.25 0 0 1 8 4.466z"/>
          </svg>
          刷新
        </button>
      </div>
      
      <div class="songs-list">
        <div v-if="favorites.length === 0" class="empty-state">
          <div class="empty-icon">♥</div>
          <h3>还没有喜欢的音乐</h3>
          <p>找到你喜欢的音乐并点击收藏按钮</p>
          <button class="browse-btn" @click="$router.push('/')">浏览音乐</button>
        </div>
        
        <div v-else>
          <!-- 表格头部 -->
          <div class="table-header">
            <div class="header-cell header-index">#</div>
            <div class="header-cell header-title">标题</div>
            <div class="header-cell header-artist">艺人</div>
            <div class="header-cell header-album">专辑</div>
            <div class="header-cell header-duration">时长</div>
            <div class="header-cell header-actions"></div>
          </div>
          
          <!-- 歌曲列表 -->
          <div class="song-item" v-for="(song, index) in favorites" :key="song.id">
            <div class="song-rank">{{ index + 1 }}</div>
            <div class="song-title-section">
              <img v-if="song.cover" :src="song.cover" :alt="song.name" class="song-thumbnail">
              <MusicIcon v-else :size="40" class="song-thumbnail" />
              <div class="song-details">
                <div class="song-name">{{ song.name }}</div>
                <div class="song-artist-mobile">{{ song.singer }}</div>
              </div>
            </div>
            <div class="song-artist">{{ song.singer }}</div>
            <div class="song-album">{{ song.album || '未知专辑' }}</div>
            <div class="song-duration">{{ formatDuration(song.duration) }}</div>
            <div class="song-actions">
              <button class="action-btn favorited" @click="removeFavorite(song)" title="取消收藏">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                  <path d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
                </svg>
              </button>
              <button class="action-btn" @click="playMusic(song)">▶</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    </div>
  </CustomScrollbar>
</template>

<script>
import MusicIcon from '@/components/MusicIcon.vue'
import CustomScrollbar from '@/components/CustomScrollbar.vue'
import { playlistAPI } from '@/utils/api'

export default {
  components: {
    MusicIcon,
    CustomScrollbar
  },
  name: 'FavoritesView',
  data() {
    return {
      favorites: []
    }
  },
  async mounted() {
    await this.loadFavorites()
  },
  methods: {
    async loadFavorites() {
      try {
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        
        console.log('开始加载收藏，检查token:', {
          hasToken: !!userToken,
          tokenLength: userToken?.length,
          expiry: userExpiry,
          isExpired: userExpiry ? Date.now() > parseInt(userExpiry) : 'no expiry'
        })
        
        if (!userToken || userToken === 'null' || userToken === '' || userToken.length <= 20) {
          console.log('Token无效，无法加载收藏')
          this.favorites = []
          return
        }
        
        if (!userExpiry || Date.now() > parseInt(userExpiry)) {
          console.log('Token已过期，无法加载收藏')
          this.favorites = []
          // 清理过期token
          localStorage.removeItem('userToken')
          localStorage.removeItem('userInfo')
          localStorage.removeItem('userTokenExpiry')
          
          // 提示用户重新登录
          if (window.app && window.app.showToast) {
            window.app.showToast('登录已过期，请重新登录', 'warning')
          }
          return
        }
        
        console.log('Token验证通过，开始请求收藏列表')
        const response = await playlistAPI.getFavorites(0, 50)
        console.log('收藏列表响应:', response)
        
        if (response.success && response.favorites) {
          this.favorites = response.favorites.map(item => ({
            id: item.music.musicId,
            name: item.music.name,
            singer: item.music.singer,
            album: item.music.album || '未知专辑',
            cover: item.music.coverPath,
            duration: item.music.duration,
            filePath: item.music.filePath,
            addedDate: new Date(item.favoriteTime || item.addTime)
          }))
          console.log('加载收藏音乐成功:', this.favorites.length, '首')
          
          // 同步更新store中的收藏列表
          if (this.$store) {
            const favoriteIds = this.favorites.map(item => item.id)
            this.$store.commit('player/SET_FAVORITES', favoriteIds)
          }
        } else if (!response.success) {
          console.warn('加载收藏失败:', response.message)
          this.favorites = []
          
          // 只在确实需要时才显示错误提示，不清理token
          if (response.message && response.message.includes('认证失败')) {
            if (window.app && window.app.showToast) {
              window.app.showToast('收藏列表加载失败，请刷新页面重试', 'warning')
            }
          }
        }
      } catch (error) {
        console.error('加载收藏音乐失败:', error)
        
        // 网络错误不应该清理token
        if (error.message && error.message.includes('Network Error')) {
          console.warn('网络连接错误，请检查后端服务是否启动')
          if (window.app && window.app.showToast) {
            window.app.showToast('网络连接失败，请检查网络连接', 'error')
          }
          this.favorites = []
          return
        }
        
        // 只有明确的认证错误才清理token
        if (error.response?.status === 401) {
          console.warn('401认证失败，但保持登录状态，仅清空收藏列表')
          this.favorites = []
          
          if (window.app && window.app.showToast) {
            window.app.showToast('收藏列表暂时无法加载，请稍后重试', 'warning')
          }
        } else if (error.response?.status === 500) {
          console.error('服务器内部错误')
          if (window.app && window.app.showToast) {
            window.app.showToast('服务器错误，请稍后重试', 'error')
          }
          this.favorites = []
        } else {
          console.error('其他错误:', error.message)
          if (window.app && window.app.showToast) {
            window.app.showToast('加载收藏失败，请稍后重试', 'error')
          }
          this.favorites = []
        }
      }
    },
    async playMusic(song) {
      try {
        console.log('播放音乐:', song.name)
        
        // 构建播放列表（收藏音乐列表）
        const playlist = this.favorites.map(s => ({
          musicId: s.id,
          id: s.id,
          title: s.name,
          name: s.name,
          singer: s.singer,
          artist: s.singer,
          cover: s.cover,
          coverPath: s.cover,
          duration: s.duration,
          filePath: s.filePath,
          src: s.filePath || s.src
        }))
        
        // 设置播放列表
        this.$store.commit('player/SET_PLAYLIST', playlist)
        
        // 找到当前音乐在播放列表中的索引
        const currentIndex = playlist.findIndex(item => item.musicId === song.id)
        if (currentIndex !== -1) {
          this.$store.commit('player/SET_CURRENT_INDEX', currentIndex)
        }
        
        // 调用Vuex播放音乐
        const musicData = {
          musicId: song.id,
          id: song.id,
          title: song.name,
          name: song.name,
          singer: song.singer,
          artist: song.singer,
          cover: song.cover,
          coverPath: song.cover,
          duration: song.duration,
          filePath: song.filePath,
          src: song.filePath || song.src
        }
        
        console.log('播放音乐数据:', musicData)
        await this.$store.dispatch('player/playMusic', musicData)
        
        // 如果前台用户已登录，记录播放历史（异步，不阻塞播放）
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        if (userToken && userToken !== 'null' && userToken !== '' && userToken.length > 20 && userExpiry && Date.now() < parseInt(userExpiry)) {
          try {
            await playlistAPI.addPlayHistory(song.id)
          } catch (historyError) {
            console.warn('记录播放历史失败:', historyError)
            if (historyError.response?.status === 401 || historyError.response?.status === 403) {
              localStorage.removeItem('userToken')
              localStorage.removeItem('userTokenExpiry')
            }
          }
        }
      } catch (error) {
        console.error('播放音乐失败:', error)
      }
    },
    async removeFavorite(song) {
      try {
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        if (!userToken || userToken === 'null' || userToken === '' || userToken.length <= 20 || !userExpiry || Date.now() > parseInt(userExpiry)) {
          this.$toast?.error('请先登录')
          return
        }
        
        await playlistAPI.removeFavorite(song.id)
        
        // 从本地列表中移除
        const index = this.favorites.findIndex(fav => fav.id === song.id)
        if (index > -1) {
          this.favorites.splice(index, 1)
        }
        
        // 更新store中的收藏列表
        this.$store.commit('player/REMOVE_FAVORITE', song.id)
        
        this.$toast?.success(`已从收藏中移除: ${song.name}`)
        console.log('取消收藏成功:', song.name)
      } catch (error) {
        console.error('取消收藏失败:', error)
        this.$toast?.error('取消收藏失败')
        if (error.response?.status === 401 || error.response?.status === 403) {
          localStorage.removeItem('userToken')
          localStorage.removeItem('userTokenExpiry')
        }
      }
    },
    async playAllFavorites() {
      if (this.favorites.length === 0) {
        console.warn('没有收藏的音乐可以播放')
        return
      }
      
      try {
        console.log('播放全部收藏音乐:', this.favorites.length, '首')
        
        // 将收藏列表转换为播放器格式
        const playlist = this.favorites.map(song => ({
          musicId: song.id,
          id: song.id,
          title: song.name,
          name: song.name,
          singer: song.singer,
          artist: song.singer,
          cover: song.cover,
          coverPath: song.cover,
          duration: song.duration,
          filePath: song.filePath,
          src: song.filePath || song.src
        }))
        
        // 设置播放列表并播放第一首
        this.$store.commit('player/SET_PLAYLIST', playlist)
        this.$store.commit('player/SET_CURRENT_INDEX', 0)
        await this.$store.dispatch('player/playMusic', playlist[0])
        
      } catch (error) {
        console.error('播放全部收藏失败:', error)
      }
    },
    formatDuration(seconds) {
      // 处理各种输入情况
      if (seconds === null || seconds === undefined || seconds === 0) return '-'
      
      // 确保是数字类型
      const numSeconds = Number(seconds)
      if (isNaN(numSeconds) || numSeconds < 0) return '-'
      
      // 计算分钟和秒
      const minutes = Math.floor(numSeconds / 60)
      const remainingSeconds = Math.floor(numSeconds % 60)
      
      // 格式化输出
      if (minutes >= 60) {
        // 超过1小时的情况
        const hours = Math.floor(minutes / 60)
        const remainingMinutes = minutes % 60
        return `${hours}:${remainingMinutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      } else {
        // 普通情况：分:秒
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
    }
  }
}
</script>

<style scoped>
.favorites-scroll {
  height: 100%;
}

.favorites {
  padding-bottom: 24px; /* 确保底部有适当的间距 */
}

.header {
  background: linear-gradient(135deg, #450af5, #c93aab);
  padding: 32px;
  display: flex;
  align-items: flex-end;
  gap: 24px;
}

.cover-gradient {
  width: 160px;
  height: 160px;
  background: linear-gradient(135deg, #450af5, #8b1ff8);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3rem;
  color: white;
  box-shadow: 0 4px 60px rgba(0, 0, 0, 0.5);
}

.info {
  flex: 1;
}

.type {
  font-size: 12px;
  font-weight: bold;
  color: white;
  margin: 0 0 8px 0;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.title {
  font-size: 3rem;
  font-weight: bold;
  color: white;
  margin: 0 0 16px 0;
}

.stats {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
  margin: 0;
}

.content {
  padding: 32px;
  background: linear-gradient(180deg, rgba(69, 10, 245, 0.2) 0%, #121212 20%);
}

.actions {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.play-all-btn {
  background: #1DB954;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 50px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s;
}

.play-all-btn:hover:not(:disabled) {
  background: #1ed760;
  transform: scale(1.04);
}

.play-all-btn:disabled {
  background: #535353;
  cursor: not-allowed;
  opacity: 0.6;
}

.refresh-btn {
  background: none;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 12px 24px;
  border-radius: 50px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s;
}

.refresh-btn:hover {
  border-color: white;
  background: rgba(255, 255, 255, 0.1);
}

.songs-list {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  overflow: hidden;
}

.empty-state {
  text-align: center;
  padding: 64px 32px;
  color: #b3b3b3;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 24px;
  opacity: 0.5;
}

.empty-state h3 {
  color: white;
  font-size: 2rem;
  margin-bottom: 16px;
}

.browse-btn {
  background: #1DB954;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 24px;
  font-weight: bold;
  cursor: pointer;
  margin-top: 24px;
  transition: background 0.2s;
}

.browse-btn:hover {
  background: #1ed760;
}

.table-header {
  display: grid;
  grid-template-columns: 60px 1fr 200px 200px 80px 120px;
  gap: 16px;
  padding: 12px 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 8px;
}

.header-cell {
  color: #b3b3b3;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  display: flex;
  align-items: center;
}

.header-duration {
  justify-content: center;
}

.song-item {
  display: grid;
  grid-template-columns: 60px 1fr 200px 200px 80px 120px;
  gap: 16px;
  align-items: center;
  padding: 8px 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  transition: background 0.2s;
}

.song-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.song-item:last-child {
  border-bottom: none;
}

.song-rank {
  text-align: center;
  color: #b3b3b3;
  font-weight: bold;
}

.song-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.song-thumbnail {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  flex-shrink: 0;
}

.song-details {
  min-width: 0;
  flex: 1;
}

.song-artist-mobile {
  display: none;
}

.song-name {
  font-size: 16px;
  font-weight: 500;
  color: white;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 4px;
}

.song-artist {
  font-size: 14px;
  color: #b3b3b3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-album {
  color: #b3b3b3;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-duration {
  color: #b3b3b3;
  text-align: center;
  font-variant-numeric: tabular-nums;
}

.song-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.song-item:hover .song-actions {
  opacity: 1;
}

.action-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.2s;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn:hover {
  color: white;
  background: rgba(255, 255, 255, 0.1);
}

.action-btn.favorited {
  color: #1DB954 !important;
}

.action-btn.favorited svg {
  color: #1DB954 !important;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    text-align: center;
    padding: 32px 16px;
  }
  
  .cover-gradient {
    width: 192px;
    height: 192px;
  }
  
  .title {
    font-size: 3rem;
  }
  
  .content {
    padding: 16px;
  }
  
  .song-album {
    display: none;
  }
}
</style> 